package com.giscloud.amp.service.sys.impl;

import com.alibaba.fastjson.JSON;
import com.giscloud.amp.dao.AmpUpdateLogMapper;
import com.giscloud.amp.entity.AmpUpdateLog;
import com.giscloud.amp.entity.AmpUpdateLogExample;
import com.giscloud.amp.entity.dto.UpdateLogDTO;
import com.giscloud.amp.service.sys.UpdateLogService;
import com.giscloud.commons.model.Result;
import com.giscloud.datasource.page.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gxd
 * @data 2018/7/14 11:09
 */
@Service("updateLogService")
public class UpdateLogServiceImpl implements UpdateLogService {
    private final static Logger log = LoggerFactory.getLogger(UpdateLogServiceImpl.class);

    @Autowired
    AmpUpdateLogMapper ampUpdateLogMapper;

    @Override
    public PageInfo getList(UpdateLogDTO updateLogDTO) {
        log.debug("#getList parameter ={}", JSON.toJSONString(updateLogDTO));
        PageHelper.startPage(updateLogDTO.getPage(), updateLogDTO.getRows());
        Map<String,String> map = new HashMap<String,String>();
        if(updateLogDTO.getStartDate()!=null && updateLogDTO.getEndDate() != null){
            map.put("startTime" , "'"+updateLogDTO.getStartDate()+"'");
            map.put("endTime" , "'"+updateLogDTO.getEndDate()+"'");
        }

        List<Map<String,String>> ampUpdateLog = ampUpdateLogMapper.selectForPage(map);
        return PageInfo.of(ampUpdateLog);
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    @Override
    public int delete(Long logId) {
        return ampUpdateLogMapper.deleteByPrimaryKey(logId);
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    @Override
    public Result add(AmpUpdateLog ampUpdateLog) {
        try {
            ampUpdateLogMapper.insertSelective(ampUpdateLog);
            return Result.success("添加成功");
        } catch (Exception e) {
            return Result.success("添加失败");
        }
    }

    @Override
    public AmpUpdateLog getRecently() {
        AmpUpdateLogExample ampUpdateLogExample = new AmpUpdateLogExample();
        AmpUpdateLogExample.Criteria criteria = ampUpdateLogExample.createCriteria();
        criteria.andStatusCdEqualTo(1);
        ampUpdateLogExample.setOrderByClause("created_dt DESC");
        List<AmpUpdateLog> list = ampUpdateLogMapper.selectByExample(ampUpdateLogExample);
        if(list.size() >0 ){
            return list.get(0);
        }else{
            return null;
        }
    }
}
